package org.yxing.palpalgps.activity;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MyHttp {
    private static final int READ_TIMEOUT = 5000;
    
    public static String getPostResponse(String spec, String data) throws MalformedURLException, IOException {
        URL url = null;
        url = new URL(spec);
        
        String result = null;
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setReadTimeout(READ_TIMEOUT);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        
        //write
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(data);
        out.flush();
        out.close();
        
        int nRC = conn.getResponseCode();
        System.out.println(nRC);
        if (nRC == HttpURLConnection.HTTP_OK) {
            
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String s;
            StringBuilder builder = new StringBuilder();
            while ((s = br.readLine()) != null)
                builder.append(s);
            
            result = builder.toString();
        }
        conn.disconnect();
        
        return result;
    }
}
